<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { useVbenModal } from '@vben/common-ui';

import { Switch } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { generateUniqueCode } from '#/utils';

interface SpecItem {
  id: number;
  group_id: number;
  post_id: number;
  name: string;
  type: string;
  status: number;
  options: string[];
  value: string;
  list_order: number;
}
interface RowData {
  [key: string]: any;
}

const state: { attributes: SpecItem[]; group_index: number; specs: any[] } =
  reactive({
    specs: [],
    attributes: [],
    group_index: -1,
  });


 const generateCombinations = (
  options: any,
  index = 0,
  current: string[] = [],
): string[][] => {
  if (index === options.length) {
    return [current];
  }

  const result: string[][] = [];
  for (const option of options[index]) {
    result.push(
      ...generateCombinations(options, index + 1, [...current, option]),
    );
  }
  return result;
};

const fixedFields = [
  { field: 'image', title: '图片',width:100, cellRender: { name: 'CellUpload' ,props: { multiple: true } } },
  { field: 'single_image', title: '色号',width:100, cellRender: { name: 'CellUpload'  } },

  
  { field: 'price', title: '售价', editRender: { name: 'input' } },
  { field: 'cost', title: '成本价', editRender: { name: 'input' } },
  { field: 'stock', title: '库存', editRender: { name: 'input' } },
  { field: 'bar_code', title: '条形码', editRender: { name: 'input' } },
  { field: 'weight', title: '重量(KG)', editRender: { name: 'input' } },
  { field: 'volume', title: '体积(m³)', editRender: { name: 'input' } },
  {
    field: 'is_default_select',
    title: '默认选中规格',
    slots: { default: 'is_default_select' },
  },
  { field: 'is_show', title: '是否显示', slots: { default: 'is_show' } },
];



const columns: any = computed(() => {

  const dynamicColumns = state.attributes.map((spec) => ({
    field: spec.name,
    title: spec.name,
    fixed: false,
  }));
  return [...dynamicColumns, ...fixedFields];
});

import {computed } from 'vue';


const tableData = computed(() => {

  const combinations = generateCombinations(
    state.attributes.map((spec) => spec.options),
  );

  const specs = combinations.map((combo) => {
    const row: RowData = {};
    state.attributes.forEach((spec, index) => {
      row[spec.name] = combo[index];
    });
    fixedFields.forEach((field: any) => {
      row[field.field] = '';
      if (field.field === 'is_default_select') row[field.field] = 0;
      if (field.field === 'is_show') row[field.field] = 1;
    });

    // 生成 suk 字符串: 组合中的选项，以逗号分隔
    row.suk = state.attributes
      .map((_spec, specIndex) => combo[specIndex])
      .join(',');

    // 生成唯一值 unique: 基于当前时间戳和随机数生成
    row.unique = generateUniqueCode();
    return row;
  });

  if (state.specs.length > 0) {
    // 对比两个数组
    specs.forEach((spec) => {
      const matchingSpec = state.specs.find(
        (oldSpec) => oldSpec.suk === spec.suk,
      );
      if (matchingSpec) {
        // 如果找到匹配的项，将 id 和 unique 从 item2 复制到 item1
        Object.assign(spec, matchingSpec);
      }
    });
  }
  return specs;
});


const [Grid, gridApi] = useVbenVxeGrid({});

// 表格监听事件集
const gridEvents: VxeGridListeners<RowData> = {
 
  editClosed: (editData: { row: any; rowIndex: number }) => {
    console.log(editData.row)
    console.log(editData.rowIndex)
    const row = editData.row;
    const rowIndex = editData.rowIndex;
    delete row._X_ROW_KEY;
    tableData.value[rowIndex] = row;
  },
};


const [SpecFormModal, SpecFormModalApi] = useVbenModal({
  fullscreenButton: true,
  onConfirm() {

    SpecFormModalApi.setData({
      value: tableData.value,
    });
    SpecFormModalApi.close();
  },
  onOpenChange(isOpen) {

    if (!isOpen) {
    
        return;
    };
    const modalData = SpecFormModalApi.getData();
    state.specs = modalData?.specs ?? [];
    state.attributes = modalData?.attributes ?? [];
    state.group_index = modalData.group_index;

    gridApi.setGridOptions({
      border: true,
      columns: columns.value,
      data: tableData.value,
      keepSource: true,
      scrollX: {
        enabled: true,
      },
      rowConfig:{
        height:60
      },
      pagerConfig: {
        enabled: false,
      },
      editConfig: {
        trigger: 'click',
        mode: 'row',
      },
    });
  },
});


const onChange = (row: any, index: number) => {
  tableData.value.forEach((item) => {
    item.is_default_select = 0;
  });
  if (!tableData.value[index]) return;
  row.is_default_select = 1;
  delete row._X_ROW_KEY;
  tableData.value[index] = row;
};

const onChange1 = (row: any, index: number) => {
  tableData.value[index] = row;
 
};



</script>

<template>
  <SpecFormModal class="w-3/5 spec-container">
    <Grid :grid-events="gridEvents">
      <template #is_default_select="{ row, rowIndex }">
        <Switch
          v-model:checked="row.is_default_select"
          :checked-value="1"
          :un-checked-value="0"
          @change="(checked) => onChange(row,rowIndex)"
        />
      </template>
      <template #is_show="{ row,rowIndex }">
        <Switch
          v-model:checked="row.is_show"
          :checked-value="1"
          :un-checked-value="0"
          checked-children="显示"
          un-checked-children="隐藏"
           @change="onChange1(row, rowIndex)"
        />
      </template>
    </Grid>
  </SpecFormModal>
</template>

<style lang="scss" scoped>
/* 添加样式细节 */
:deep(.ant-upload-list-item-container) {
  width: 50px !important;
  height: 50px !important;
}


</style>
